﻿using Microsoft.VisualStudio.TestTools.UITest.Common;
using System;

namespace AXExtension.Filters
{
	/// <summary>
	/// Makes sure that DropDown menus aren't cached by the playback
	/// system. When DropDown elements are cached errors occur whenever
	/// two different DropDowns are opened in quick succession.
	/// </summary>
	class DropdownUncachingFilter : Filter
	{
		public DropdownUncachingFilter()
		{
			Require(stack => stack.Peek().UIElement.Parent() != null &&
				stack.Peek().UIElement.Parent().Name == "DropDown");
		}

		public override void Run(IUITestActionStack stack)
		{
			var item = stack.Peek().UIElement.Parent();
			// It's important not to throw away the existing search
			// configuration information. Unfortunately, it's also
			// not mutable inline, so we have to make a new array.
			string[] previousConfiguration = item.QueryId.SearchConfigurations;
			string[] configuration = new string[previousConfiguration.Length + 1];
			Array.Copy(previousConfiguration, configuration, previousConfiguration.Length);

			// AlwaysSearch is the configuration that disables caching
			// of the element.
			configuration[previousConfiguration.Length] = "AlwaysSearch";
			item.QueryId.SearchConfigurations = configuration;
		}
	}
}
